package uform.model.value;

import thx.util.Result;
import thx.error.Error;
import thx.error.AbstractMethod;
using thx.util.Results;

class FloatType<T : Float> extends ValueType<T>
{
	static var _re = ~/^\s*([-+]?[0-9]+\.?[0-9]+(?:[eE][-+]?[0-9]+)?)\s*/m;
	
	public function new()
	{
		super();
	}
	
	override function validateType(value : Dynamic) : Result
	{
		if (Std.is(value, Float))
			return Result.Ok;
		else
			return "expected type {0} but was {1}".failure(["Float", Types.typeName(value)]);
	}

	override function _parse(s : String, ?ref : { s : String }) : T
	{
		var re = _pattern();
		if (!re.match(s))
			throw new Error("unable to parse float value {0:T,20}", s);
		if (null != ref)
			ref.s = re.matchedRight();
			
		var s = re.matched(1);
		if (s.substr(0, 1) == '+')
			s = s.substr(1);
		return _parseString(s);
	}
	
	function _parseString(s : String) : T
	{
		return cast Std.parseFloat(s);
	}
	
	function _pattern() : EReg
	{
		return _re;
	}
	
	public static function trimStartingPlus(value : String)
	{
		if (value.substr(0, 1) == '+')
			return value.substr(1);
		else
			return value;
	}
}